package sf.view.fields;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

import sf.jsonloader.JsonLoader;
import sf.model.fields.ZoomFieldModel;

public class ZoomFieldFactory implements AbstractFieldFactory {
	@SuppressWarnings("unchecked")
	public HashMap<String, AbstractField> getFields(String tableCode) {
		HashMap<String, AbstractField> fields = new HashMap<String, AbstractField>();
		JsonLoader jloader = JsonLoader.getInstance();

		ArrayList refs = (ArrayList) jloader.get(tableCode, "outRefs");
		ArrayList columns = (ArrayList) jloader.get(tableCode, "columns");

		for (int i = 0; i < refs.size(); i++) {
			HashMap ref = (HashMap) refs.get(i);
			String primaryTargetFieldCode = getPrimaryTargetCode(ref);
			ZoomFieldModel zfm = new ZoomFieldModel();
			zfm.setParentTableCode((String) ref.get("parentTable"));
			zfm.setPrimaryTargetField(primaryTargetFieldCode);

			ArrayList joins = (ArrayList) ref.get("joins");
			LinkedHashMap<String, String> joinTypes = getJoinTypes(joins,
					columns);
			zfm.setTypes(joinTypes);
			zfm.setSize(joinTypes.size()*4);
			// String primaryType = joinTypes.remove(primaryTargetFieldCode);
			// String primaryTargetChildCode =

			// String primaryTypeRegex =
			// TypeRegexConverter.getRegex(primaryType);
			// String remainingRegex = TypeRegexConverter.getRegexForComposite(
			// "-", joinTypes.values());
			// zfm.setPatternByString(remainingRegex + "-" + primaryTypeRegex);
			ZoomField zf = new ZoomField();
			zf.setModel(zfm);
			zf.setLabelText((String) ref.get("name"));

			fields.put((String) ref.get("code"), zf);
		}

		return fields;
	}

	@SuppressWarnings("unchecked")
	private String getPrimaryTargetCode(HashMap reference) {
		JsonLoader jloader = JsonLoader.getInstance();

		ArrayList columns = (ArrayList) jloader.get((String) reference
				.get("parentTable"), "columns");

		for (int i = 0; i < columns.size(); i++) {
			HashMap column = (HashMap) columns.get(i);
			if ((Boolean) (column).get("primary")
					&& !((Boolean) (column).get("foreign")))
				return (String) column.get("code");
		}

		return null;
	}

	@SuppressWarnings("unchecked")
	private HashMap getColumn(ArrayList columns, String columnCode) {
		for (Object c : columns) {
			HashMap hc = (HashMap) c;
			if (hc.get("code").equals(columnCode)) {
				return hc;
			}
		}

		return null;
	}

	@SuppressWarnings("unchecked")
	private LinkedHashMap<String, String> getJoinTypes(ArrayList joins,
			ArrayList columns) {
		LinkedHashMap<String, String> joinTypes = new LinkedHashMap<String, String>();

		for (Object j : joins) {
			HashMap join = (HashMap) j;
			String columnCode = (String) join.get("parentTableColumnCode");
			HashMap column = getColumn(columns, columnCode);
			String type = (String) column.get("dataType");
			joinTypes.put(columnCode, type);
		}

		return joinTypes;
	}
}
